<template>
  <div class="warpper-box">
    <div class="inner_box">
      <div class="node-box">
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="line-box">
              <div class="line-bg">
                <label>分类列表</label>
                <el-button type="primary" size="mini" @click="add(true)"
                  >添加分类</el-button
                >
              </div>
              <div class="tree-prop">
                <el-tree
                  :data="treeData"
                  :props="treeProps"
                  node-key="id"
                  @node-click="handleNodeClick"
                  default-expand-all
                  :expand-on-click-node="false"
                >
                </el-tree>
              </div>
            </div>
          </el-col>
          <el-col :span="18">
            <div class="line-box">
              <div class="line-bg">
                <label>{{visible ? '新增分类':'编辑分类'}}</label>
              </div>
              <div class="tree-form">
                <el-form
                  :model="ruleForm"
                  ref="ruleForm"
                  size="small"
                  label-width="110px"
                >
                  <el-form-item
                    label="排序号"
                    prop="sortNumber"
                    :rules="[
                      { required: true, message: '输入排序号', trigger: 'blur' }
                    ]"
                  >
                    <el-input-number
                      v-model="ruleForm.sortNumber"
                      :step="1"
                      step-strictly
                    ></el-input-number>
                  </el-form-item>
                  <el-form-item
                    label="类别名称"
                    prop="categoryName"
                    :rules="[
                      {
                        required: true,
                        message: '输入类别名称',
                        trigger: 'blur'
                      }
                    ]"
                  >
                    <el-input v-model="ruleForm.categoryName"></el-input>
                  </el-form-item>
                  <el-form-item label="上级类别名称">
                    <div class="tree-box">
                      <i
                        class="el-icon-arrow-up tree-icon"
                        :class="[show2Tree ? 'tree-icon-action' : '']"
                      ></i>
                      <el-input
                        readonly
                        v-model="ruleForm.parentCategoryName"
                        @focus="show2Tree = true"
                        @blur="blurs2"
                        placeholder="请选择"
                      ></el-input>
                      <el-tree
                        v-if="show2Tree"
                        :data="treeData"
                        :props="treeProps"
                        default-expand-all
                        @node-click="handleCheckChange"
                        class="tree-select"
                      />
                    </div>
                  </el-form-item>
                  <el-form-item label="备注">
                    <el-input
                      type="textarea"
                      :rows="3"
                      v-model="ruleForm.remarks"
                    ></el-input>
                  </el-form-item>
                </el-form>
                <div class="btns">
                  <el-button
                    type="primary"
                    size="medium"
                    style="width:200px;"
                    @click="onFormSubmit('ruleForm', false)"
                    :disabled="!ruleForm.categoryName"
                    >提交</el-button
                  >
                  <template v-if="!visible">
                     <el-button
                      type="danger"
                      size="medium"
                      style="width:200px;"
                      :disabled="!ruleForm.categoryName"
                      @click="ondel()"
                      >删除</el-button
                    >
                  </template>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
import {
  getSupplierCategoryTree,
  supplierCategoryDel,
  supplierCategorySave
} from "@/api/supplier_api";
export default {
  data() {
    return {
      visible: true,
      treeData: [],
      treeProps: {
        label: "categoryName",
        children: "children"
      },
      show2Tree: false,
      showTree: false,
      ruleForm: {
        id: "",
        sortNumber: "",
        categoryName: "",
        parentCategoryName: "",
        parentCategoryId: "",
        remarks: ""
      }
    };
  },
  computed: {
    ...mapGetters(["findType"])
  },
  mounted() {
    this.loadList(true);
  },
  methods: {
    async loadList() {
      const { code, data } = await getSupplierCategoryTree();
      if (code == 200) {
        this.treeData = data;
      }
    },
    add(flag) {
      this.visible = true;
      this.ruleForm = {
        id: "",
        sortNumber: "",
        categoryName: "",
        parentCategoryName: "",
        parentCategoryId: "",
        remarks: ""
      };
    },
    blurs2() {
      setTimeout(() => {
        this.show2Tree = false;
      }, 200);
    },
    blurs() {
      setTimeout(() => {
        this.showTree = false;
      }, 200);
    },
    handleCheckChange(data) {
      if (this.ruleForm.categoryName === data.categoryName) {
         this.ruleForm.parentCategoryName = ''
        this.$message.error('上级分类不能为当前分类！')
        return;
      }
      this.ruleForm.parentCategoryName = data.categoryName;
      this.ruleForm.parentCategoryId = data.id;
      console.log(this.ruleForm);
      console.log(data);
    },
    handleNodeClick(data) {
      let result = this.findParents(this.treeData, data.parentCategoryId);
      if (result.length) {
        const obj = result.at(-1);
        this.ruleForm.parentCategoryName = obj.categoryName;
        this.ruleForm.parentCategoryId = obj.id;
      } else {
        this.ruleForm.parentCategoryName = "";
        this.ruleForm.parentCategoryId = "";
      }
      this.ruleForm.id = data.id;
      this.ruleForm.categoryName = data.categoryName;
      this.ruleForm.sortNumber = data.sortNumber;
      this.ruleForm.remarks = data.remarks;
      this.visible = false
    },
    findParents(array, id) {
      let parentArray = [];

      if (array.length === 0) {
        return parentArray;
      }

      function recursion(arrayNew, id) {
        for (let i = 0; i < arrayNew.length; i++) {
          let node = arrayNew[i];
          if (node.id === id) {
            parentArray.unshift(node);
            recursion(array, node.parentCategoryId);
            break;
          } else {
            if (!!node.children) {
              recursion(node.children, id);
            }
          }
        }
        return parentArray;
      }
      let arrayNew = array;
      parentArray = recursion(arrayNew, id);
      return parentArray;
    },
    ondel() {
      let name = `确认删除分类${this.ruleForm.categoryName}？`;
      let param = {};
      param.id = this.ruleForm.id;
      this.$confirm(name, "温馨提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { code, msg } = await supplierCategoryDel(param);
          if (code === 200) {
            this.add(false);
            this.loadList();
          }
        })
        .catch(() => {});
    },
    onFormSubmit(formName) {
      this.$refs[formName].validate(async valid => {
        if (valid) {
          const { code, msg } = await supplierCategorySave(this.ruleForm);
          if (code === 200) {
             this.add(false);
            this.loadList();
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped>
.node-box {
  padding: 10px 20px;
}
.line-box {
  border: 1px solid rgb(235, 238, 244);
}
.line-bg {
  display: flex;
  margin-bottom: 10px;
  border-bottom: 1px solid rgb(235, 238, 244);
  padding: 10px;
  align-items: center;
  justify-content: space-between;
  background: rgb(250, 250, 250);
  height: 50px;
}
.tree-prop {
  height: calc(100vh - 238px);
  overflow: auto;
}
.tree-form {
  height: calc(100vh - 238px);
  padding: 30px;
}
.tree-box {
  position: relative;
}
.tree-select {
  position: absolute;
  z-index: 99999;
  border: 1px solid rgb(235, 238, 244);
  background-color: #fff;
  height: 200px;
  width: 100%;
  padding: 10px;
  overflow-y: auto;
}
.tree-icon {
  position: absolute;
  z-index: 99999;
  right: 10px;
  top: 10px;
  color: #c0c4cc;
  font-size: 14px;
  transition: transform 0.3s, -webkit-transform 0.3s;
  transform: rotateZ(180deg);
  cursor: pointer;
}
.tree-icon-action {
  -webkit-transform: rotateZ(0);
  transform: rotateZ(0);
}
.btns {
  display: flex;
  align-items: center;
  grid-column-gap: 20px;
  margin-top: 50px;
  margin-left: 110px;
}
</style>
